var g_priceScale = 2;
g_product = 'pms';
/////////////////////////// tab bar ///////////////////////////////////////////
function getNearForm(btn) {
	return $(btn).closest('.jform');
}
function getPopupTabTarget(btn) {
	var v = btn.getAttribute('value');
	if (v == null) {
		v = $(btn).html();
	}
	return '_popupTab_' + getModelName(getNearForm(btn)) + ':' + v;
}
function addRecord(btn, url) {
	submitPage(btn, buildRequest(btn, 'add',url));
}
function _addRecord(btn, url) {
	openLink(buildRequest(btn, '_add',url), getPopupTabTarget(btn), getText('commons.add'), btn);
}

function _copyRecord(btn, url) {
	submitSelectedPageinfo(btn, url, '_copy', true);
}

function _quoteByInventoryRecord(btn, url) {
	submitSelectedPageinfo(btn, url, '_quoteByInventory', true);
}

function _addAvabRecord(btn, url) {
	openLink(buildRequest(btn, '_addAvab',url), getPopupTabTarget(btn), getText('action._addAvab'), btn);
}
function _updateRecordInBlank($tr, url, id) {
	openBlank($tr, url + id + '&_layout=whole');
}
function _acceptRecord($tr, url, id) {
	var title = getModelName($tr.closest('.jform')) + ':' + getText('commons.accept');
	openMainTab(url + id, title, null, $tr);
}

function _importLayoutRecord(btn) {
	var $btn = $(btn);
	var $form = $btn.closest('.jform');
	var title = getModelName($form) + ':' + $btn.html();
	var url = g_base_site + '/espirit/eap/pagelayout/pageUpgrade._importLayout.html';
	openMainTab(url, title, null, btn);
}
function exportLayoutRecord(btn) {
	openBlank(btn, g_base_site + '/espirit/eap/pagelayout/pageUpgrade.exportLayout.html?', true);
}
function exportLayoutWithDataRecord(btn) {
	openBlank(btn, g_base_site + '/espirit/eap/pagelayout/pageUpgrade.exportLayoutWithData.html?', true);
}

function printRecord(btn, url) {
	/*if (!url) {		
		var $form = $(btn).closest('.jform');
		url = $form.attr('action');
	}
	var extraParams = 'path=' + url;
	var printUrl = buildRequest(btn, 'print', url, extraParams);
	openBlank(btn, printUrl);*/
	webprint(btn, url);
}
function webprint(btn, url) {
	if (!existsSelectedItem(btn)){
		infoPleaseSelectRecord();
		return;
	}
	
	if (!url) {		
		var $form = $(btn).closest('.jform');
		url = $form.attr('action');
	}
	
	var idObjs = $("[name$='.id']", getActiveDom());
	var params = "";
	idObjs.each(function() {
		var idObj = this;
		if (idObj.checked) {
			params = params + '&model.id=' + idObj.value;
			return true;
		}
	});
	var printUrl = buildRequest(btn, 'print', url);
	if (printUrl.indexOf('?') == -1) {
		printUrl += '?_resultCode=$print' + params;
	} else {		
		printUrl += '&_resultCode=$print' + params;
	}
	window.open(printUrl, 'print', 'status=no,menubar=yes,location=no');
}
function showPrintPreview() {
	//window.print();
}

function _searchRecord(btn, url) {
	var name = btn.getAttribute('name');
	if (name == 'execute._smartSearch') {
		_smartSearch(btn, url);
	} else if (name == 'execute._searchWeb') {
		_searchWeb(btn, url);
	} else {
		var title = btn.getAttribute('value');
		if (title == null) {
			title = $(btn).html();
		}
		if (!title) {
			title = getText('commons.search');
		}
		openLink(buildRequest(btn, '_search',url), getPopupTabTarget(btn), title, btn);
	}
}
function _searchWeb(btn, url) {
	var partNumber = getPartNumber();
	if (partNumber){
		url += '?model.elecEventItem.partNumber=' + partNumber;
	}
	var target = btn.getAttribute('value');
	if (target == null) {
		target = $(btn).html();
	}
	openLink(buildRequest(btn, '_search',url), target, target, btn);
}
function _smartSearch(btn, url) {
	// bad design, add here temporarily
	var partNumber = getPartNumber();
	if (partNumber){
		url += '?model.elecEventItem.partNumber=' + partNumber;
	}
	var target = btn.getAttribute('value');
	if (target == null) {
		target = $(btn).html();
	}
	openLink(buildRequest(btn, '_search',url), target, target, btn);
}

function _webSearch(btn, url) {
	// bad design, add here temporarily
	var partNumber = getPartNumber();
	if (partNumber){
		url += '?model.elecEventItem.partNumber=' + partNumber;
	}
	var target = btn.getAttribute('value');
	if (target == null) {
		target = $(btn).html();
	}
	openLink(buildRequest(btn, '_search',url), target, target, btn);
}

function submitSelectedPageinfo(btn, url, targetMethod, selectOneAtLeast) {
	var params = getSelectedPageinfoIds(btn);
	if (selectOneAtLeast && Object.keys(params).length == 0) {
		infoPleaseSelectRecord();
		return;
	}
	
	var hasSeparator = url && (url.indexOf('?') >= 0);
	url = buildRequest(btn, targetMethod, url) + (hasSeparator?'':'?') + toParameters(params);
	var title = getModelName(getNearForm(btn)) + ':' + $(btn).html();
	openMainTab(url, title, null, btn);
}
function _quoteRecord(btn, url) {
	submitSelectedPageinfo(btn, url, '_quote', true);
}

function _mergeRecord(btn, url) {
	submitSelectedPageinfo(btn, url, '_merge', true);
}

function changePassword(btnObj) {
	var $form = $(btnObj).closest('.jform');
	var password1 = $('[name=password]', $form).val();
	var password2 = $('[name=password2]', $form).val();

	if (password1 != password2) {
		showError(g_text['errors.passwordNotMatched']);
	} else {
		ajaxSubmit($form, {
			success: function(data) {
				var $data = $(data);
				if ($data.hasClass('error')) {
					showError($data.html());
				} else {
					showSuccess(g_text['user.changePassword.success']);
				}
			}
		});
	}
}

function _addFromCarRecord(btn, url) {
	submitSelectedPageinfo(btn, url, '_addFromCar', false);
}

function _generatePLFromCarRecord(btn, url) {
	submitSelectedPageinfo(btn, url, '_generatePLFromCar', true);
}

function _generateChargeOrderRecord(btn, url) {
	submitSelectedPageinfo(btn, url, '_generateChargeOrder', true);
}

function _generatePaymentRecord(btn, url) {
	submitSelectedPageinfo(btn, url, '_generatePayment', true);
}

function _generateReceiptRecord(btn, url) {
	submitSelectedPageinfo(btn, url, '_generateReceipt', true);
}

function _generateInvoiceRecord(btn, url) {
	submitSelectedPageinfo(btn, url, '_generateInvoice', true);
}

function _searchWebRecord(btn, url) {
	var partNumber = getPartNumber();
	if (partNumber){
		url += '?model.elecEventItem.partNumber=' + partNumber;
	}
	submitPage(btn, buildRequest(btn, '_searchWeb',url), getPopupTabTarget(btn),true);
}

function _generateSalesOrderRecord(btn, url) {
	submitSelectedPageinfo(btn, url, '_generateSalesOrder', true);
}

function _approveRecord(btn, url) {
		var selectedIds = getSelectedPageinfoIds(btn);
	var selectedCount = Object.keys(selectedIds).length;
	if (selectedCount == 0){
		infoPleaseSelectRecord();
		return;
	}
	//should select only one record
	if (selectedCount > 1){
		info(g_text['commons.onlyOneRecordPermit']);
		return;
	}
	
	var url = buildRequest(btn, '_approve', url) + '?' + toParameters(selectedIds);
	var $btn = $(btn);
	var $form = $btn.closest('.jform');
	var title = getModelName($form) + ':' + $btn.html();
	openMainTab(url, title, null, btn);
}

function _generatePLRecord(btn, url) {
	submitSelectedPageinfo(btn, url, '_generatePL', true);
}

function _generateInstockByPORecord(btn, url) {
	submitPage(btn, buildRequest(btn, '_generateInstockByPO',url), getPopupTabTarget(btn),true);
}

function _generateInstockByRMARecord(btn, url) {
	submitPage(btn, buildRequest(btn, '_generateInstockByRMA',url), getPopupTabTarget(btn),true);
}

function _generateVRMARecord(btn, url) {
	submitSelectedPageinfo(btn, url, '_generateVRMA', true);
}

function _receiveRecord(btn, url) {
	submitSelectedPageinfo(btn, url, '_receive', true);
}


function _shipRecord(btn, url) {
	submitSelectedPageinfo(btn, url, '_ship', true);
}


function _generatePackingListRecord(btn, url) {
	submitSelectedPageinfo(btn, url, '_generatePackingList', true);
}

function offRecord(btn, targetUrl) {
	var $form = $(btn).closest('.jform');
	var $datagrid = $form.find('.tablelist:first');
	var elementName = $datagrid.closest('.jdatagrid').attr('fullName');
    targetUrl += "?_resultCode=$element&_elementName=" + elementName;

	ajaxSubmit($datagrid, {
		url: targetUrl,
		success:function(data) {
			var $data = $(data);
			if ($data.hasClass('error')) {
				showError($data.html());
			} else {
				$datagrid.replaceWith(data);
			}
		}
	});
}

function _generatePerformanceInvoiceRecord(btn, url) {
	submitSelectedPageinfo(btn, url, '_generatePerformanceInvoice', true);
}

function _needToBuyRecord(btn, url) {
	submitSelectedPageinfo(btn, url, '_needToBuy', true);
}

function _changeRecord(btn, url) {
	submitSelectedPageinfo(btn, url, '_change', true);
}


function _allocateRecord(btn, url) {
	submitSelectedPageinfo(btn, url, '_allocate', true);
}

function _generatePOFromSINeedToBuyRecord(btn, url) {
	submitSelectedPageinfo(btn, url, '_generatePOFromSINeedToBuy', true);
}

function _generateOfferFromSINeedToBuyRecord(btn, url) {
	submitSelectedPageinfo(btn, url, '_generateOfferFromSINeedToBuy', true);
}

function _generateOfferByRfqRecord(btn, url) {
	submitSelectedPageinfo(btn, url, '_generateOfferByRfq', true);
}


function _batchOfferRecord(btn, url) {
	submitSelectedPageinfo(btn, url, '_batchOffer', true);
}

function _generateRMAFromPackingListRecord(btn, url) {
	submitSelectedPageinfo(btn, url, '_generateRMAFromPackingList', true);
}

function _generateSalesOrderInvoiceRecord(btn, url) {
	submitSelectedPageinfo(btn, url, '_generateSalesOrderInvoice', true);
}

function _allocateQtyRecord(btn,url) {
	var params = getSelectedPageinfoIds(btn);
	var selectedCount = Object.keys(params).length;
	if (selectedCount == 0) {
		infoPleaseSelectRecord();
		return;
	}
	if (selectedCount > 1){
		info(g_text['commons.onlyOneRecordPermit']);
		return;
	}
	
	var modelId = '';
	for (var key in params) {
		modelId = params[key];
		break;
	}
	checkUrl = g_base_site+'/espirit/sale/salesOrderItem.canAllocateQty.html?model.id=' + modelId;
	$.ajax({
		   url: checkUrl,
		   success: function(response) {
				if (response =='false'){
					info(g_text['commons.eventItem.canntAllocateQty']);
					return;
				} else {
					submitSelectedPageinfo(btn, url, '_allocateQty', true);
				}
		   },
		   data: {_resultCode: '$json' } 
	});

//	submitPage(btn,buildRequest(btn, '_allocateQty',url), getPopupTabTarget(btn),true);
}

function _generateDeliveryRecord(btn, url) {
	submitSelectedPageinfo(btn, url, '_generateDelivery', true);
}

function _generateSORecord(btn, url) {
	submitSelectedPageinfo(btn, url, '_generateSO', false);
}

function _generateQuoteRecord(btn, url) {
	submitSelectedPageinfo(btn, url, '_generateQuote', false);
}
function _generatePurchaseOrderRecord(btn, url) {
	submitSelectedPageinfo(btn, url, '_generatePurchaseOrder', true);
}

function _generatePORecord(btn, url) {
	submitSelectedPageinfo(btn, url, '_generatePO', true);
}

function addFromCarRecord(btn, url) {
	if (!existsSelectedItem(btn)){
		infoPleaseSelectRecord();
		return;
	}
	
	// Special Logic for salesOrderItem
	var $form = $(btn).closest('.jform');
	var action = $form.attr('action');
	var isSalesOrderItem = action.indexOf('salesOrderItem') > 0;
	if (isSalesOrderItem) {
		var params = serialize($form);
		var sParams = '';
		for (var key in params) {
			var newKey = key.replace('results','carItems');
			sParams += '&' + newKey + '=' + params[key];
		}
		sParams = sParams.replace('results','carItems');
		openLink(g_base_site + '/espirit/sale/salesOrderItem._generatePL.html?' + sParams, g_text['model.espirit.sale.packingList'], g_text['model.espirit.sale.packingList']);
	} else {		
		submitPage(btn, url);
	}
}
function removeRecord(btn, url) {
	if (!existsSelectedItem(btn)){
		infoPleaseSelectRecord();
		return;
	}
	var $form = $(btn).closest('.jform');
	var newUrl = buildRequest(btn, 'remove',url);
	$.ajax({
		url: newUrl,
		data: serialize($form),
		success:function(data) {
			var $data = $(data);
			if ($data.hasClass('error')) {
				showError($data.html());
			} else {
				refreshCurrentTab();
			}
		}
	});
//	submitPage(btn, url, '_hidden');
//	submitPage(btn, buildRequest(btn, 'remove',url), '_hidden');
}

function addToCarRecord(btn, url) {
	if (!existsSelectedItem(btn)){
		infoPleaseSelectRecord();
		return;
	}
	var url = buildRequest(btn, "addToCar",url) + '?_resultCode=$noResult';
	var $form = $(btn).closest('.jform');
	var data = serialize($form);
	$.post(url, data);
	
	//mock message impletention
	showSuccess(g_text['commons.addToCarSucess']);
}
// add web search item to shopping cart
function addToCar(linkObj, id) {
	if ($(linkObj).hasClass('itemExisted')) {
		var url = g_base_site + '/espirit/common/netSearch.remove.html?_resultCode=$noResult&results[0].id=' + id;
		$.get(url, function() {
			$(linkObj).removeClass('itemExisted');
			showSuccess(g_text['commons.removeFromCarSucess']);
		});
	} else {
		var url = g_base_site + '/espirit/common/netSearch.addToCar.html?_resultCode=$noResult&results[0].id=' + id;
		$.get(url, function() {
			$(linkObj).addClass('itemExisted');
			showSuccess(g_text['commons.addToCarSucess']);
		});
	}
}
function addToMatch(linkObj, id) {
	var rfqItemId = $(linkObj).closest('.netSearchCtn').attr('rfqItemId');
	
	var url = g_base_site + '/espirit/common/netSearch.addToMatch.html?_resultCode=$noResult&rfqItem.id=' + rfqItemId + '&model.id=' + id;
	$.get(url, function() {
		$(linkObj).addClass('itemExisted');
		showSuccess(g_text['commons.addToMatchSucess']);
	});
}
function infoPleaseSelectRecord(){
	info(g_text['commons.pleaseSelectRecord']);
}
function info(info){
	showError(info, 300);
}

function existsSelectedItem(btn){
	var $form = getNearForm(btn);
	var $pageinfo = $form.find('.jpageinfolist:first');
	var $tr = $('table:last tbody>tr:not(.childContainer)', $pageinfo);
	return $tr.find('input:checked[value]').length > 0;
}

function needToCallRecord(btn, url) {
	submitPage(btn, url, '_hidden');
}
function setCompletedFlagRecord(btn, url) {
	submitPage(btn, url, '_hidden');
}


function callOverRecord(btn, url) {
	if (!existsSelectedItem(btn)){
		infoPleaseSelectRecord();
		return;
	}
	submitPage(btn, url, '_hidden');
}

function removeMatchedItemRecord(btn, url) {
	submitPage(btn, url, '_hidden');
}
function _generateOfferRecord(btn, url) {
	var selectedIds = getSelectedPageinfoIds(btn);
	if (Object.keys(selectedIds).length == 0){
		infoPleaseSelectRecord();
		return;
	}
	var url = buildRequest(btn, '_generateOffer', url) + '?' + toParameters(selectedIds);
	var $btn = $(btn);
	var $form = $btn.closest('.jform');
	var title = getModelName($form) + ':' + $btn.html();
	openMainTab(url, title, null, btn);
}

function closeRecord(btn, url) {
	if (!existsSelectedItem(btn)){
		infoPleaseSelectRecord();
		return;
	}

	var $form = $(btn).closest('.jform');
	var newUrl = buildRequest(btn, 'close',url);
	$.ajax({
		url: newUrl,
		data: serialize($form),
		success:function(data) {
			var $data = $(data);
			if ($data.hasClass('error')) {
				showError($data.html());
			} else {
				refreshCurrentTab();
			}
		}
	});
}

function callCompleteRecord(btn, url) {
	if (!existsSelectedItem(btn)){
		infoPleaseSelectRecord();
		return;
	}

	var $form = $(btn).closest('.jform');
	var newUrl = buildRequest(btn, 'callComplete',url);
	$.ajax({
		url: newUrl,
		data: serialize($form),
		success:function(data) {
			var $data = $(data);
			if ($data.hasClass('error')) {
				showError($data.html());
			} else {
				refreshCurrentTab();
			}
		}
	});
}

function confirmRecord(btn,url,act) {
	if (!existsSelectedItem(btn)){
		infoPleaseSelectRecord();
		return;
	}
	var deleteRequest = "" + buildRequest(btn, act);
	$.confirm({
		'title'		: getText('commons.' + act),
		'message'	: getText('commons.' + act + 'Confirm'),
		'buttons'	: {
			'确认' : {
				'class'	: 'blue',
				'action': function() {
					var idObjs = $("[name$='.id']", getActiveDom());
					var params = "";
					idObjs.each(function() {
						var idObj = this;
						if (idObj.checked) {
							params = params + '&' + idObj.name + '=' + idObj.value;
						}
					});
					
					if (deleteRequest.indexOf('?') > 0) {
						deleteRequest = deleteRequest + params;
					} else {
						deleteRequest = deleteRequest + '?' + params;
					}
					openLink(deleteRequest,null,null,btn);
				}
			},
			'取消' : {
				'class'	: 'gray',
				'action': function(){}
			}
		}
	});
}

function backAcceptRecord(btn, url) {
	if (!existsSelectedItem(btn)){
		infoPleaseSelectRecord();
		return;
	}

	var $form = $(btn).closest('.jform');
	var newUrl = buildRequest(btn, 'backAccept',url);
	$.ajax({
		url: newUrl,
		data: serialize($form),
		success:function(data) {
			var $data = $(data);
			if ($data.hasClass('error')) {
				showError($data.html());
			} else {
				refreshCurrentTab();
			}
		}
	});
}

function exportToK3Record(btn, url) {
	openLink(buildRequest(btn, 'exportToK3',url, '_resultCode=$noResult'), '_blank', getText('action.exportToK3'), btn);
}

function reportRecord(btn, url) {
	var params = getSelectedPageinfoIds(btn);
	var selectedCount = Object.keys(params).length;
	if (selectedCount == 0){
		infoPleaseSelectRecord();
		return;
	}

	params._resultCode = '$noResult';
	var hasSeparator = (url.indexOf('?') >= 0);
	url = buildRequest(btn, 'report', url) + (hasSeparator?'':'?') + toParameters(params);
	openBlank(btn, url);
}

function _goNextRecord(btn, url) {
	var selectedIds = getSelectedPageinfoIds(btn);
	var selectedCount = Object.keys(selectedIds).length;
	if (selectedCount == 0){
		infoPleaseSelectRecord();
		return;
	}
	//should select only one record
	if (selectedCount > 1){
		info(g_text['commons.onlyOneRecordPermit']);
		return;
	}
	
	var url = buildRequest(btn, '_goNext', url) + '?' + toParameters(selectedIds);
	var $btn = $(btn);
	var $form = $btn.closest('.jform');
	var title = getModelName($form) + ':' + $btn.html();
	openMainTab(url, title, null, btn);
	
	/*
	$.ajax({
		   url: g_base_site+'/espirit/sale/salesOrderItem.canGoNext.html?model.id=' + selectedIdValue,
		   success: function(response) {
				var result = response.responseText;
				if (result =='false'){
					info(g_text['commons.event.canntGoNext']);
					return;
				} else {
					submitPage(btn, buildRequest(btn, '_goNext',url),getPopupTabTarget(btn), true);
				}
		   },
		   data: {_resultCode: '$json' } 
		});
	*/
//	openLink(buildRequest(btn, '_goNext',url), getPopupTabTarget(btn), getText('action._goNext'), btn);
}

function saveRfqMatchedItemRecord(btn, url) {
	submitPage(btn, buildRequest(btn, 'saveRfqMatchedItem',url), '_hidden', true);
}

function _batchAddRecord(btn, url) {
//	submitPage(btn, buildRequest(btn, '_batchAdd',url), getPopupTabTarget(btn),true);
	openLink(buildRequest(btn, '_batchAdd',url), getPopupTabTarget(btn), getText('action._batchAdd'), btn);
}

function _importFileRecord(btn, url) {
	openLink(buildRequest(btn, '_importFile',url), getPopupTabTarget(btn), getText('action._importFile'), btn);
}
function statRecord(btn) {
	var $form = $(btn).closest('.jform');
	var $target = $form.next('.statRecord');
	if ($target.length == 0) {
		$form.after('<div class="statRecord" style="clear:both"></div>');
		$target = $form.next('.statRecord');
	}
	var $tab = $form.find('.jtab').eq(0);
	var selectIndex = $tab.tabs("option", "selected");
	var options = {
		includeBlankValue: true,
		data: {
			"newSearch": true,
			"model.customerPartItemSales": selectIndex
		},
		beforeSend: function() {
			addLoading($target);
		},
		success:function(data) {
			removeLoading($target);
			$target.html(data);
		}
	};
	ajaxSubmit($form, options);
}
/**
 * Change the price, toatal price of event.ftl
 * 
 * @param inputObj
 * @param isTaxRateObj
 */
function calculateTotalPrice(inputObj, isTaxRateObj) {
	var $tr = $(inputObj).closest('tr');
	var qty = $tr.find('[name=qty]').val();
	var $price = $tr.find('[name=price]');
	var price = $tr.find('[_name=price]').val(); // the price is n't update to the hidden element at present
	if (price) {
		price = toNumber(price);
		// TODO: remove it if using price object
		if ($price.val() == '') {			
			$price.val(price);
		}
	}
	var $grossPrice = $tr.find('[name=grossPrice]');
	var grossPrice = $tr.find('[_name=grossPrice]').val();
	if (grossPrice) {
		grossPrice = toNumber(grossPrice);
		if ($grossPrice.val() == '') {			
			$grossPrice.val(grossPrice);
		}
	}
	var exchangeFrom = $grossPrice.next('input').val();
	var $curTab = getActiveDom();
	var $currency = $('[cmbname="model.currency.id"]', $curTab);
	var exchangeTo;
	if ($currency.length > 0) {
		exchangeTo = $currency.val();
	} else {
		$currency = $('[txtname="model.currency.id"]', $curTab);
		exchangeTo = $currency.text();
	}
	
	var inputObjName = $(inputObj).attr('_name');
	var triggerSharePrice = true;		// a flag to identify if the caculate the share price (freight)
	if (grossPrice && (inputObjName == 'grossPrice' || isTaxRateObj)) {
		grossPrice = Number(grossPrice);
		var taxRate = getRate('taxRate', '[name="model.taxRate.id"]');
		var exchange = getExchange(exchangeFrom, exchangeTo);
		var importRate = getRate('importRate', '[name="model.importRate.id"]');
		var serviceRate = getRate('serviceRate', '[name="model.serviceRate.id"]');
		//console.debug('taxRate=' + taxRate + ',exchange=' + exchange + ',importRate=' + importRate + ',serviceRate=' + serviceRate);
		price = grossPrice * exchange * (1 + importRate/100) * (1 + serviceRate/100) * (1 + taxRate/100);
		$price.attr('price', price);
		var rowShareCostPrice = $price.attr('sharePrice');
		if (rowShareCostPrice && rowShareCostPrice != '') {
			price += Number(rowShareCostPrice);
		}
		price = formatPrice(price);
		$price.next('input').val(exchangeTo);
		$price.val(price);
		$price.prev('input').val(price + exchangeTo);
	} else if (price && (inputObjName == 'price' || isTaxRateObj)) {
		// TODO: now, only use the simple logic to calculate the total price
		triggerSharePrice = false;
		$price.attr('price', price);
		price = Number(price);
		var rate = getRate('taxRate', '[name="model.taxRate.id"]');
		grossPrice = price / (1 + rate/100);
		grossPrice = formatPrice(grossPrice);
		var $grossPrice = $tr.find('[name=grossPrice]');
		$grossPrice.val(grossPrice);
		$grossPrice.prev('input').val(grossPrice + $grossPrice.next('input').val());
	}
	
	if (qty && grossPrice) {
		qty = Number(qty);
		grossPrice = Number(grossPrice);
		price = Number(price);
		var total = qty * grossPrice;
		
		//var totalTaxPrice = total + total * getRate() / 100;
		var totalTaxPrice = qty * price; 
		// format the price, only show 2 decimals
		var sTotal = formatPrice(total, 2);
		var sTotalTaxPrice = formatPrice(totalTaxPrice, 2);
		
		var e = new $.Event('change', {'manual': true});
		$tr.find('[txtname=grossAmount]').html(sTotal + exchangeTo).trigger(e);
		e = new $.Event('change', {'manual': true});
		$tr.find('[txtname=amount]').html(sTotalTaxPrice + exchangeTo).trigger(e);
		if (triggerSharePrice) {
			calculateSharePrice();
		}
	}
}
/**
 * Change the share price of event.ftl
 */
function calculateSharePrice() {
	var $curTab = getActiveDom();
	var $freight = $('[name="model.freight"]', $curTab);
	if ($freight.length == 0) {
		return;
	}
	
	var freight = $freight.val();
	if (freight && freight != '') {
		freight = Number(freight);
	} else {
		freight = 0;
	}
	var totalAmount = 0;
	$('[txtname=amount]', $curTab).each(function() {
		var sValue = $(this).html();
		if (sValue != '') {						
			totalAmount += toNumber(sValue);
		}
	})
	var exchangeTo = $('[cmbname="model.currency.id"]', $curTab).val();
	$('[name=price]', $curTab).each(function() {
		if (!exchangeTo) {
			exchangeTo = $('[cmbname="model.currency.id"]', $curTab).val();
		}
		var $tr = $(this).closest('tr');
		var qty = Number($tr.find('[name=qty]').val());
		var amount = toNumber($tr.find('[txtname=amount]').html());
		if (amount != 0 && qty != 0) {
			//console.debug('freight=' + freight + ',qty=' + qty + ',amount=' + amount + ',totalAmount=' + totalAmount);
			var sharePrice = freight * (amount/totalAmount) / qty;
			//console.debug('sharePrice=' + sharePrice);
			$(this).attr('sharePrice', sharePrice);
			var sPrice = $(this).attr('price');
			if (!sPrice) {
				//recalculate the price, TODO: optimize it
				var grossPrice = $tr.find('[_name=grossPrice]').val();
				if (grossPrice) {
					grossPrice = toNumber(grossPrice);
					var taxRate = getRate('taxRate', '[name="model.taxRate.id"]');
					var $grossPrice = $tr.find('[name=grossPrice]');
					var exchangeFrom = $grossPrice.next('input').val();
					var $curTab = getActiveDom();
					var $currency = $('[cmbname="model.currency.id"]', $curTab);
					var exchangeTo;
					if ($currency.length > 0) {
						exchangeTo = $currency.val();
					} else {
						$currency = $('[txtname="model.currency.id"]', $curTab);
						exchangeTo = $currency.text();
					}
					var exchange = getExchange(exchangeFrom, exchangeTo);
					var importRate = getRate('importRate', '[name="model.importRate.id"]');
					var serviceRate = getRate('serviceRate', '[name="model.serviceRate.id"]');
					var price = grossPrice * exchange * (1 + importRate/100) * (1 + serviceRate/100) * (1 + taxRate/100);
					sPrice = price;
				} else {
					sPrice = $(this).val();
				}
			}
			var price = Number(sPrice);
			price += sharePrice;
			var totalTaxPrice = qty * price;
			
			price = formatPrice(price);
			var $this = $(this);
			$this.val(price);
			$this.prev('input').val(price + $this.next('input').val())
			var sTotalTaxPrice = formatPrice(totalTaxPrice, 2);
			$tr.find('[txtname=amount]').html(sTotalTaxPrice + exchangeTo);
		}
	});
}
var rates = {};
function getRate(service, objSelector) {
	var rateId = $(objSelector, getActiveDom()).val();
	if (rateId && rateId != '') {
		var key = service + ',' + rateId;
		if (rates[key] == null) {
			var url = g_base_site + '/espirit/eap/manager/' + service + '.getRate.html?_resultCode=$json&id=' + rateId;
			$.ajax({
				url:url,
				async:false,
				success:function(data) {
					rates[key] = Number(data);
				}
			});
		}
		return rates[key];
	}
	return 0;
}
var exchanges = {};
function getExchange(fromCcy, toCcy) {
	if (fromCcy !='' && toCcy != '') {
		var key = fromCcy + ',' + toCcy;
		if (exchanges[key] == null) {
			var url = g_base_site + '/espirit/eap/manager/exchangeRate.getExchangeByCode.html?_resultCode=$json&from=' + fromCcy + '&to=' + toCcy;
			$.ajax({
				url:url,
				async:false,
				success:function(data) {
					data = $.parseJSON(data);
					if (data.error) {
						showError(data.error);
					} else {						
						exchanges[key] = Number(data);
					}
				}
			});
		}
		if (exchanges[key] == null) {
			return 1;
		} else {			
			return exchanges[key];
		}
	}
	return 1;
}
function formatPrice(num, dec) {
	if (!dec) {
		dec = g_priceScale;
	}
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}

function backRecord(btn,url) {
	if (!existsSelectedItem(btn)){
		infoPleaseSelectRecord();
		return;
	}
	var deleteRequest = "" + buildRequest(btn, 'back');
	$.confirm({
		'title'		: getText('commons.back'),
		'message'	: getText('commons.backConfirm'),
		'buttons'	: {
			'确认' : {
				'class'	: 'blue',
				'action': function() {
					var idObjs = $("[name$='.id']", getActiveDom());
					var params = "";
					idObjs.each(function() {
						var idObj = this;
						if (idObj.checked) {
							params = params + '&' + idObj.name + '=' + idObj.value;
						}
					});
					
					if (deleteRequest.indexOf('?') > 0) {
						deleteRequest = deleteRequest + params;
					} else {
						deleteRequest = deleteRequest + '?' + params;
					}
					openLink(deleteRequest,null,null,btn);
				}
			},
			'取消' : {
				'class'	: 'gray',
				'action': function(){}
			}
		}
	});
}

function searchPartItem() {
	var url = g_base_site + '/espirit/eap/manager/partItem.showPartItemInfo.html?model.id=' + $('#partItemSearch_hidden').val();
	openLink(url, 'partItem', 'partItem');
}
function searchSmart() {
	var $table = $('.jpageinfo table:first', getActiveDom());
	var $selectedRow = $table.find('tr.current');
	var partNumber = $('[txtName$="partNumber"],[txtName="partItem.id"]', $selectedRow).text();
	if (partNumber == null || partNumber == '') {
		var $datagridTable = $('.tablelist', getActiveDom());
		var $tr = $('.selected', $datagridTable);
		partNumber = $tr.find('[cmbname="partItem.id"]').val();
	}
	var method = 'search'
	if (partNumber == null || partNumber == '') {
		partNumber = '';
		method = '_search';
	} 
	openMainTab(g_base_site + '/espirit/common/smartSearch.' + method + '.html?fromMenu=true?newSearch=true&model.partNumber=' + partNumber,g_text['智能查询'],'智能查询');
}
function searchWeb() {
	var $table = $('.jpageinfo table:first', getActiveDom());
	var $selectedRow = $table.find('tr.current');
	var partNumber = $('[txtName$="partItem.id"]', $selectedRow).text();
	openMainTab(g_base_site + '/espirit/common/netSearch._searchWeb.html?searchText=' + partNumber,g_text['网上查询'],'网上查询');
}

function submitLog(btn) {
	if ($(btn).hasClass("disabled")) {
		return;
	}
	
	var $input = $(btn).closest('.sysLogInput').find('input:first');
	if ($input.val() !='') {
		var $form = $(btn).closest('.jform');
		// lock the button 10 seconds to avoid duplicated click
		$(btn).addClass("disabled"); 
		setTimeout(function() {
			$(btn).removeClass("disabled");
		}, 10000);
		
		ajaxSubmit($form, {
			success:function(data) {
				$(btn).removeClass("disabled");
				var $data = $(data);
				if ($data.hasClass('error')) {
					showError($data.html());
				} else {
					$form.parent().html(data);
				}
				$data.find('.sysLogInput input:first').focus();
			}
		});
	}
}
function clickRfqItemNoticeFlag($tr, userId) {
	var $noticeFlag = $tr.find('[txtname="noticeFlag"]');
	if ($noticeFlag.length == 0) {
		return ;
	}
	var noticeFlag = $noticeFlag.text();
	if (noticeFlag) {
		var $tr = $noticeFlag.closest('tr');
		var $ownerId = $tr.find('[txtname="owner.id"]');
		var ownerId = $ownerId.text();
		if (ownerId == userId) {
			var id = $tr.find('input[type="checkbox"]').val();
			var url = g_base_site + '/espirit/sale/rfqItem.clearNoticeFlag.html?model.id=' + id;
			$.get(url, function() {
				$noticeFlag.html('');
			});
		}
	}
}

// im.notice.ftl
function openNotice(link, countId, target, text) {
	var count = Number($('#' + countId).html());
	if (count > 0) {
		var cleanLink = g_base_site + '/espirit/common/userNotice.cleanNotice.html?_resultCode=$json&type=' + countId.substring(0, countId.length - 6);
		$.get(cleanLink);
	}
	openMainTab(link, text);
	
	$('#noticeMenu').hide();
	$('#' + countId).html('0');
	var totalCount = Number($('#countNotice').html());
	var newTotalCount = totalCount - count;
	$('#countNotice').html(newTotalCount);
	if (newTotalCount == 0) {
		$('#noticeTip').hide();
	}
}

function updateNotice(notice) {
	if (!notice) {
		return;
	}
	
	// FIMXE: change notice header to RED
	var total = 0;
	total += updateNoticeToLabel('rfqNotice', notice.rfq);
	total += updateNoticeToLabel('purchaseNotice', notice.purchase);
	total += updateNoticeToLabel('approvingSINotice', notice.approvingSI);
	total += updateNoticeToLabel('approvingPINotice', notice.approvingPI);
	total += updateNoticeToLabel('approvingPLINotice', notice.approvingPLI);
	total += updateNoticeToLabel('receiveNotice', notice.receive);
	total += updateNoticeToLabel('siReceiveNotice', notice.siReceive);
	total += updateNoticeToLabel('shipNotice', notice.ship);
	total += updateNoticeToLabel('needToBuyItemNotice', notice.needToBuyItem);
	total += updateNoticeToLabel('messageNotice', notice.message);
	total += updateNoticeToLabel('rfqItemAllocateNotice', notice.rfqItemAllocate);
	if (total == 0) {
		$('#noticeTip').hide();
	} else {
		$('#noticeTip').show();
		$('#countNotice').html(total);
	}
}
function updateNoticeToLabel(id, val) {
	if (!val) {
		val = 0;
	}
	var $label = $('#' + id);
	if ($label.length > 0) {
		$label.html(val);
		return val;
	} else {
		return 0;
	}
}
function loadAndUpdateNotice() {
	$.ajax({
		url: g_base_site + '/espirit/common/userNotice.view.html?_resultCode=$json&properties=id,rfq,purchase,message,receive,ship,siReceive,approvingSI,approvingPI,approvingPLI,needToBuyItem,rfqItemAllocate',
		success: function(data) {
			try {
				var jsonData = $.parseJSON(data);
				updateNotice(jsonData);
			} catch(ex) {
				$('#noticeArea').html(data);
			}
		}
	});
}

//im.notice.ftl - end